package com.handy.webwork.plugin;

import java.util.ArrayList;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.handy.webwork.config.HandyConfiguration;

/**
 * 插件监听器.<br>
 * 在应用中扩展了IPlugin接口的类通过addLintener添加到插件监听器.
 * @author rocken.zeng@gmail.com
 *
 */
public class PluginNotifier {
	private static Log log = LogFactory.getLog(PluginNotifier.class);
	private static PluginNotifier instance = null;
	private ArrayList<IPlugin> listeners = null;
	
	/**
	 * 私有构造
	 */
	private PluginNotifier(){
		listeners = new ArrayList<IPlugin>();
	}
	
    /**
     * 单例
     * @return
     */
	public static synchronized PluginNotifier getInstance() {
        if (instance == null) {
            instance = new PluginNotifier();
            instance.loadPlugin();
        }
        return instance;
    }
	
	/**
	 * 将所有插件实例加入到插件监听器中。
	 */
	@SuppressWarnings("unchecked")
	private void loadPlugin(){
		for (PluginBean plugin : HandyConfiguration.Plugins()) {
			if (null == plugin.getEntry() || "".equals(plugin.getEntry())){
				continue;
			}
			IPlugin iplugin = null;
			try {
				//实例化所有插件类加入到插件监听器中。
				Class<IPlugin> c = (Class<IPlugin>) Class.forName(plugin.getEntry());
				iplugin = c.newInstance();
				if (null!=iplugin){
					iplugin.setBean(plugin);
					listeners.add(iplugin);
				}
			} catch (ClassNotFoundException e) {
				log.error("该类未找到："+plugin.getEntry()+"，请定义该类。");
			} catch (InstantiationException e) {
				log.error(e.getMessage());
			} catch (IllegalAccessException e) {
				log.error(e.getMessage());
			}
		}
	}
    
    /**
     * 执行所有插件的start方法。
     */
    @SuppressWarnings("unchecked")
	public static void run() {
		for (IPlugin plugin : getInstance().listeners) {
			plugin.run();
		}
	}
    
    /**
     * 执行所有插件的destroy方法。
     */
    public static void destroy(){
		for (IPlugin plugin : getInstance().listeners) {
			plugin.destroy();
		}
    }
    
}
